#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, base64, time, json, hashlib
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcsl_v1_5
from Crypto.PublicKey import RSA
from django_redis import get_redis_connection
from Crypto.Cipher import AES
from django.conf import settings

from equity_mall.utils.utils import trans_xml_to_dict
from activities.models import Channel


def wyf_access_token():
    redis_conn = get_redis_connection("gzh_accesstoken")
    access_token = redis_conn.get("wyf_access_token")
    if not access_token:
        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7da420ea681c863a&secret=7057b94cc7f6fcc9d8355aabe99367d5'
        response = requests.get(url=url)
        result = response.json()
        access_token = result['access_token']
        expires_in = result['expires_in']
        redis_conn = get_redis_connection("gzh_accesstoken")
        redis_conn.setex("wyf_access_token", expires_in, access_token)
        return access_token
    else:
        access_token = access_token.decode()
        return access_token


def get_sign_sha1(params_list):
    params_list.sort()
    params_str = "".join(u"{}".format(params) for params in params_list)
    sha1 = hashlib.sha1()
    sha1.update(params_str.encode('utf-8'))
    sign = sha1.hexdigest()
    return sign


def pkcs7_padding_encoder(text):
    key = 'OEujnhZWs1Z2rqj40paD0CU0mNRDvR0FqeEkyuTb7Gt='
    iv = 'OEujnhZWs1Z2rqj4'
    key =base64.b64decode(key.encode('utf-8'))
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = str(cryptor.decrypt(text))
    plain_text = plain_text[plain_text.find('<xml>'):plain_text.rfind('</xml>')+6]
    plain_dict = trans_xml_to_dict(plain_text)
    return plain_dict


def get_wyf_result(body=None, action=None, url=None):
    redis_conn = get_redis_connection("gzh_accesstoken")
    access_token = redis_conn.get("wyf_access_token")
    if not access_token:
        cookie = Channel.objects.get(id=6)
        access_token = cookie.token
        url = url.replace('ACCESS_TOKEN', access_token)
        if action == 'POST':

            response = requests.post(url=url, data=body, )




if __name__ == '__main__':
    print(wyf_access_token())
